//
//  TWFXFutureWeatherViewController.m
//  TWFXWeather
//
//  Created by Lion User on 13-10-14.
//  Copyright (c) 2013年 Lion User. All rights reserved.
//

#import "TWFXFutureWeatherViewController.h"

@interface TWFXFutureWeatherViewController ()

@end

static int indexOfDownLoad = -1;
CGFloat heightOfScreen;

@implementation TWFXFutureWeatherViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        
        self.singleClass = [TWFXSingleClass sharedTWFXSingleClass];
        
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(notification_currentCityChanged)
                                                     name:self.singleClass.notificationName_currentCityIsChangedToTrend
                                                   object:nil];
        
        
        self.activity = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
        self.activity.hidden = NO;
        
        self.activityItem = [[[UIBarButtonItem alloc] initWithCustomView:self.activity] autorelease];;
        
        
        UIBarButtonItem *rightbar = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(downLoadCityWeatherData)] autorelease];
        
        UIBarButtonItem *leftbar = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSearch target:self action:@selector(goCityListView)] autorelease];
        
        UIBarButtonItem *backbar = [[[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStyleBordered target:self action:nil] autorelease];
        
        self.refleshItem = rightbar;
        self.navigationItem.rightBarButtonItem = rightbar;
        self.navigationItem.leftBarButtonItem = leftbar;
        self.navigationItem.backBarButtonItem = backbar;
        
        
        self.cityListViews = [[[NSMutableArray alloc] init] autorelease];
        
        self.cityListVC = [[[TWFXCityListViewController alloc] initWithNibName:nil bundle:nil] autorelease];
        
        
        int index = self.singleClass.indexOfCurrentCity;
        self.currentCity = self.singleClass.cityDataList[index];
        
        
        self.dealDataOfDownLoad = [[[TWFXDealWeatherDataOfDownLoad alloc] init] autorelease];
        self.dealDataOfDownLoad.delegateOfDealData = self;
        
    }
    
    return self;
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    
    //#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000
    if([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0)
    {
        //边缘延伸的属性.这个属性指定导航栏的四个边缘是否向外延伸？解决导航栏和状态栏重叠的问题
        self.edgesForExtendedLayout = UIRectEdgeNone;
        
        //设置导航栏的样式，默认是白底黑字那个样式，设成title的颜色是白色的那个样式
        [self.navigationController.navigationBar setBarStyle:UIBarStyleBlack];
        
        //设置导航栏的背景色，会影响到状态栏
        [self.navigationController.navigationBar setBarTintColor:[UIColor grayColor]];
        
        
        
        //指定了当Bar使用了不透明图片时，视图是否延伸至Bar所在区域，默认值时NO
        //     self.extendedLayoutIncludesOpaqueBars = NO;
        
        //    self.modalPresentationCapturesStatusBarAppearance = NO;
        
        //设置导航栏是否背景透明?会影响到导航栏里后面被push进来的view里的导航栏是否占用空间
        self.navigationController.navigationBar.translucent = NO;
        
    }
    //#endif  // #if __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000
    
    
    
    //获取屏幕的高度(不含状态栏)
    heightOfScreen = [UIScreen mainScreen].applicationFrame.size.height;
    CGFloat heightOfView = heightOfScreen - 44 - 49;
    
    self.bgView = [[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, heightOfView + 49)] autorelease];
    self.bgView.contentMode = UIViewContentModeScaleAspectFill;
    [self.view addSubview:self.bgView];
    
    
    UIScrollView *scrollView = [[[UIScrollView alloc] init] autorelease];
    scrollView.frame = CGRectMake(10, 10, 300, heightOfView - 20);
    
    scrollView.scrollEnabled = YES;
    scrollView.alwaysBounceVertical = NO;
    scrollView.alwaysBounceHorizontal = YES;
    scrollView.showsHorizontalScrollIndicator = YES;
    scrollView.pagingEnabled = YES;
    scrollView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.4];
    scrollView.delegate = self;
    self.scroll = scrollView;
    [self.view addSubview:self.scroll];
    [scrollView release];
    
    
    
    UIPageControl *pageControl = [[UIPageControl alloc] init];
    //  pageControl.center = CGPointMake(self.view.frame.size.width/2, heightOfScreen - 44 - 49 - 10);  // 设置pageControl的位置
    //   [pageControl setBounds:CGRectMake(0,0,16*(pagesCount-1)+16,16)]; //页面控件上的圆点间距基本在16左右。
    
    
    //uipagecontrol放在scrollview里,距底部10像素处
    pageControl.frame = CGRectMake(10, self.scroll.frame.origin.y + self.scroll.frame.size.height - 20, 300, 20);
     [pageControl addTarget:self action:@selector(pageTurn:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:pageControl];
    self.page = pageControl;
    [pageControl release];
    
    
    
    //给控件添加阴影
    CALayer *capa = self.scroll.layer;
    
    //给元素添加四周圆角
    capa.cornerRadius = 10.0f;
    capa.masksToBounds = YES;
    capa.opaque = NO;
    
    [self creatCityListViews];
    [self refreshUI];
}


-(void) navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    //    if ([TWFXSingleClass sharedTWFXSingleClass].isCurrentCityChanged) {
    //
    //        [TWFXSingleClass sharedTWFXSingleClass].isCurrentCityChanged = NO;
    //
    //        self.currentCity = [TWFXSingleClass sharedTWFXSingleClass].currentCityInfo;
    //        [self refreshUI];
    //    }
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"FutureWeatherPage"];
}

//每次显示页面时,把currentCity属性指向单例类的currentCityInfo
-(void) viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    
    [self.activity stopAnimating];
    self.navigationItem.rightBarButtonItem = self.refleshItem;
    
    
    [MobClick beginLogPageView:@"FutureWeatherPage"];
    
    int index = self.singleClass.indexOfCurrentCity;
    
    self.currentCity = self.singleClass.cityDataList[index];
    self.scroll.contentOffset = CGPointMake(300 * index, 0);
    
    self.page.numberOfPages = self.singleClass.cityDataList.count;
    self.page.currentPage = index;
    
    
    //城市列表发生改变,重新构造scroll里的view,设置scroll的contentOffset滚动到当前显示的cityview
    if(self.singleClass.isCityListInfosChangedToTrend)
    {
        [self creatCityListViews];
        
        self.singleClass.isCityListInfosChangedToTrend = NO;
        self.singleClass.isCurrentCityChangedToTrend = NO;
        
        [self refreshUI];
    }
    
    //切换了当前显示的城市,scroll要设置显示坐标
    else if (self.singleClass.isCurrentCityChangedToTrend)
    {
        self.singleClass.isCurrentCityChangedToTrend = NO;
        
    }
    
}


-(void)creatCityListViews
{
    [self.cityListViews removeAllObjects];
    
    for (UIView *subview in self.scroll.subviews) {
        [subview removeFromSuperview];
    }
    
    self.scroll.contentSize = CGSizeMake(300 * self.singleClass.cityDataList.count , self.scroll.frame.size.height);
    for (int i = 0; i < [TWFXSingleClass sharedTWFXSingleClass].cityDataList.count; i++) {
        
        
        //对于controller而言,要设置它的view.frame时,已经要加载view了,所以view里面的控件的位置和大小已经定了
        //之所以还是要设置她得frame,是为了把它固定到scroll里一个固定的位置
        CGRect rect = CGRectMake(i * 300, 0, self.scroll.frame.size.width, self.scroll.frame.size.height - 20);
        
        TWFXFutureWeatherView *tempWeather = [[TWFXFutureWeatherView alloc] initWithFram:rect WeatherInfo:[TWFXSingleClass sharedTWFXSingleClass].cityDataList[i]];
        
        [self.scroll addSubview:tempWeather];
        [self.cityListViews addObject:tempWeather];
        [tempWeather release];
    }
    
}




//当前城市发生更换,比如由 广州 换成 宁波
- (void)notification_currentCityChanged
{
    int index = self.singleClass.indexOfCurrentCity;
    self.currentCity = self.singleClass.cityDataList[index];
    [self refreshUI];
}



-(void)goCityListView
{
    self.cityListVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController  pushViewController:self.cityListVC animated:YES ];
}


#pragma mark- ScrollView的代理方法


//切换城市
-(void)scrollViewDidEndDecelerating:(UIScrollView*)scrollView
{
    int index = scrollView.contentOffset.x / 300;
    
    self.singleClass.indexOfCurrentCity = index;
    self.page.currentPage = index;
    
    self.singleClass.isCityListInfosChangedToRealTime = YES;
    [self.singleClass saveIndexOfCurrentCityToUserDefault];
    
    self.currentCity = self.singleClass.cityDataList[index];
    
    [self refreshUI];
}


-(void)pageTurn:(UIPageControl*)pageControl{
    
    int index = pageControl.currentPage;
    
    self.scroll.contentOffset = CGPointMake(300*index, 10);
    
    self.singleClass.indexOfCurrentCity = index;
    
    self.singleClass.isCityListInfosChangedToRealTime = YES;
    [self.singleClass saveIndexOfCurrentCityToUserDefault];
    
    self.currentCity = self.singleClass.cityDataList[index];
    
    [self refreshUI];
}


#pragma mark- 设置背景


//根据天气状况设置背景
-(void)setBackgroud:(NSString *)weather
{
    NSString *str_nameOfbg = [self nameOfBackgroud:weather];
    UIImage *bg = [UIImage imageNamed:str_nameOfbg];
    
    [self.bgView setImage:bg];
    self.bgView.contentMode = UIViewContentModeScaleAspectFill;
}


//根据天气情况返回背景图的路径
-(NSString*)nameOfBackgroud:(NSString *)weather
{
    NSString *nameOfbg = nil;
    
    if (weather == nil)
    {
        nameOfbg = @"nodata.jpg";
    }
    else if ([weather rangeOfString:@"晴"].length > 0)
    {
        nameOfbg = @"sunny.jpg";
    }
    else if ([weather rangeOfString:@"云"].length > 0)
    {
        nameOfbg = @"cloudy.jpg";
    }
    else if ([weather rangeOfString:@"阴"].length > 0)
    {
        nameOfbg = @"shade.jpg";
    }
    else if ([weather rangeOfString:@"雨"].length > 0)
    {
        nameOfbg = @"rain.jpg";
    }
    else if ([weather rangeOfString:@"雪"].length > 0)
    {
        nameOfbg = @"snow.jpg";
    }
    else if ([weather rangeOfString:@"尘"].length > 0)
    {
        nameOfbg = @"dust.jpg";
    }
    else if ([weather rangeOfString:@"霾"].length > 0)
    {
        nameOfbg = @"dust.jpg";
    }
    else if ([weather rangeOfString:@"雾"].length > 0)
    {
        nameOfbg = @"fog.jpg";
    }
    else
    {
        nameOfbg = @"other.jpg";
    }
    
    return nameOfbg;
}


#pragma mark- 下载天气数据及相关回调函数

-(void)downLoadCityWeatherData
{
    //navigationItem的rightbar切换成菊花
    self.navigationItem.rightBarButtonItem = self.activityItem;
    [self.activity startAnimating];
    
    indexOfDownLoad = self.singleClass.indexOfCurrentCity;
    [self.dealDataOfDownLoad initCityInfoOfDownLoad:self.currentCity indexOfCurrentCity:indexOfDownLoad];
    [self.dealDataOfDownLoad beginDownLoadCityWeatherData];
}


-(void) DownLoadDataHavedDealed:(TWFXStruct_AllWeatherInfo *)cityWeather
{
    [self.activity stopAnimating];
    self.navigationItem.rightBarButtonItem = self.refleshItem;
    
    
    //下载不成功时
    UIAlertView *alertView = nil;
    if (cityWeather == Nil)
    {
        
        alertView = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"网络连接失败,请稍后再试" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alertView show];
        [alertView release];
        return;
    }
    else if(cityWeather.futureWeatherInfo == nil || cityWeather.realTimeWeatherInfo == nil)
    {
        
        alertView = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"下载出现了异常,请稍后再试" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alertView show];
        [alertView release];
        return;
    }
    
    
    //下载的天气信息是当前城市的
    if ([self.currentCity.countID isEqualToString:cityWeather.countID]) {
        
        self.singleClass.cityDataList[indexOfDownLoad] = cityWeather;
        self.currentCity = cityWeather;
        
        self.singleClass.isCityListInfosChangedToRealTime = YES;
        [self.singleClass saveCityListToUserDefault];
        
        [self refreshCityViewUI:cityWeather];
        
        [self refreshUI];
    }
    //否则遍历citylist里的所有城市,看是哪一个城市的天气信息
    else
    {
        for (int i = 0; i < self.singleClass.cityDataList.count; i++) {
            
            TWFXStruct_AllWeatherInfo * temp  = self.singleClass.cityDataList[i];
            
            
            if ([cityWeather.countID isEqualToString:(temp.countID)])
            {
                self.singleClass.cityDataList[i] = cityWeather;
                
                indexOfDownLoad = i;
                [self refreshCityViewUI:cityWeather];
                
                self.singleClass.isCityListInfosChangedToTrend = YES;
                [self.singleClass saveCityListToUserDefault];
            }
        }
        
    }
    
}



#pragma mark- 刷新界面

//下载了哪个城市的天气就刷新对应的view
-(void)refreshCityViewUI:(TWFXStruct_AllWeatherInfo*) cityDataOfDownLoad
{
    ((TWFXFutureWeatherView*)self.cityListViews[indexOfDownLoad]).weather = self.singleClass.cityDataList[indexOfDownLoad];
    [self.cityListViews[indexOfDownLoad] setNeedsDisplay];
}


- (void)refreshUI
{
    self.navigationItem.title = self.currentCity.countName;
    [self setBackgroud:self.currentCity.futureWeatherInfo.img_title1];
    
}



- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    
    float sysVer =[[[UIDevice currentDevice] systemVersion] floatValue];
    
    //ios 6.0 及之后才执行以下代码,ios6.0之前是通过调用viewWillUnload来处理
    if (sysVer>= 6.0f)
    {
        if ([self.view window] == nil)// 是否是正在使用的视图
        {
            // Add code to preserve data stored in the views that might be
            // needed later.
            
            // Add code to clean up other strong references to the view in
            // the view hierarchy.
            
            self.bgView = nil;
            self.cityVC = nil;
            
            self.view = nil;// 目的是再次进入时能够重新加载调用viewDidLoad函数。
        }
    }
    
}



- (void)dealloc
{
    
    [_activity release];
    [_currentCity release];
    [_cityListVC release];
    
    self.cityVC = nil;
    
    [super dealloc];
}



@end









